package com.habdqn.easybuy.dao.impl;

import com.habdqn.easybuy.dao.BaseDao;
import com.habdqn.easybuy.dao.OrderDetailDao;
import com.habdqn.easybuy.entity.Order;
import com.habdqn.easybuy.entity.OrderDetail;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Xing.Jiejian
 * @date 2020/12/3
 */
public class OrderDetailDaoImpl extends BaseDao implements OrderDetailDao {
    private String baseSelect = "SELECT id, order_id, product_id, product_quantity FROM order_detail";


    /**
     * 通过实体作为筛选条件查询
     *
     * @param orderId 订单编号
     * @return 对象列表
     */
    @Override
    public List<OrderDetail> queryByOrder(int orderId) {
        String sql = baseSelect + " WHERE order_id=?";
        return getListByRS(executeQuery(sql,orderId));
    }

    /**
     * 新增数据
     *
     * @param orderDetail 实例对象
     * @return 影响行数
     */
    @Override
    public int insert(OrderDetail orderDetail) {
        String sql = "INSERT INTO order_detail( order_id, product_id, product_quantity) VALUES(?, ?, ?) ";
        return executeInsert(sql, orderDetail.getOrderId(),orderDetail.getProductId(),orderDetail.getProductQuantity());
    }

    /**
     * 通过订单编号删除数据
     *
     * @param orderId 订单编号
     * @return 影响行数
     */
    @Override
    public int deleteByOrder(int orderId) {
        String sql = "DELETE FROM order_detail WHERE order_id=?";
        return executeUpdate(sql,orderId);
    }

    /**
     * 从结果集中提取对象集合
     *
     * @param rs 结果集
     * @return 订单集合
     */
    private List<OrderDetail> getListByRS(ResultSet rs) {
        List<OrderDetail> orderDetails = null;
        try {
            if (rs != null) {
                orderDetails = new ArrayList<>();
                while (rs.next()) {
                    OrderDetail orderDetail = new OrderDetail();
                    orderDetail.setId(rs.getInt("id"));
                    orderDetail.setOrderId(rs.getInt("order_id"));
                    orderDetail.setProductId(rs.getInt("product_id"));
                    orderDetail.setProductQuantity(rs.getInt("product_quantity"));
                    orderDetails.add(orderDetail);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return orderDetails;
    }
}
